<?php
namespace app\pay\service;

use think\Controller;
class Hqbase extends Controller
{
	/**
	 * 统一下单接口
	 * @param $data
	 * @param string $apiUrl
	 * @return bool|mixed|string
	 */
	protected function unified($data,$apiUrl=""){
		if(empty($data)){return false;}
		if(empty($apiUrl)){
			$apiUrl=$this->apiUrl;
		}
		$data = $this->getPaySign($data);//halt($data);
		$data = json_encode($data);
		$res = $this->post_json($data,$apiUrl);//halt($res);
		$res = json_decode($res,true);
		file_put_contents("hqxe.txt",var_export($res,true)."\n\n",FILE_APPEND);
		return $res;
		if($res["returncode"] != "0000"){
			return $res;
		}else{
			$verifyRes = $this->verifySign($res["sign"],$res);
			if($verifyRes){
				return $res;
			}else{
				return false;
			}
		}

	}

	//签名
	protected function getPaySign(array $data)
	{
		$tempArr = $data;
		$str="";
		unset($tempArr['sign']);
		ksort($tempArr);
		foreach ($tempArr as $k => $v) {
			$v=(string)($v);
			if(!empty($v) || $v==0){
				$str .= "{$k}={$v}";
			}
		}

		$sign = md5($str.$this->signKey);
		$data["sign"] = $sign;
		return $data;
	}


	//验证签名
	protected function verifySign($sign,$data){
		$reSign = $this->getPaySign($data);
		if ($reSign == $sign) {
			return true;
		} else {
			return false;
		}
	}


	/**
	 * 支付post+json提交
	 * @author QQ
	 */
	protected function post_json($jsonStr, $url="")
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
				'Content-Type: application/json; charset=utf-8',
				'Content-Length: ' . strlen($jsonStr)
			)
		);
		$response = curl_exec($ch);
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch);
		return $response;
	}
}